import { defineStore } from 'pinia';
import piniaPersistConfig from './piniaPersist';
import router from '@/routers/index';

/* tabsMenuProps */
export interface TabsMenuProps {
	icon: string;
	title: string;
	path: string;
	close: boolean;
}

/* TabsState */
export interface TabsState {
	tabsMenuList: TabsMenuProps[];
}

// TabsStore
export const TabsStore = defineStore({
	id: 'TabsState',
	state: (): TabsState => ({
		tabsMenuList: [],
	}),
	getters: {},
	actions: {
		async initTabs() {
			const tabsParams = {
				icon: '',
				title: '工作台',
				path: '/dashboard/workspace',
				name: 'Workspace',
				close: false,
			};
			if (this.tabsMenuList.filter((v) => v.title === '工作台').length <= 0) {
				this.tabsMenuList.push(tabsParams);
			}
		},
		// Add Tabs
		async addTabs(tabItem: TabsMenuProps) {
			// not add tabs white system
			if (this.tabsMenuList.every((item) => item.path !== tabItem.path)) {
				if (this.tabsMenuList.every((v) => v.title === '工作台')) {
					await this.initTabs();
				}
				if (tabItem.path === '/' || tabItem.path === '/dashboard/workspace' || tabItem.path.startsWith('/redirect')) {
					return;
				}
				this.tabsMenuList.push(tabItem);
			}
		},
		// Remove Tabs
		async removeTabs(tabPath: string, isCurrent = true) {
			const tabsMenuList = this.tabsMenuList;
			if (isCurrent) {
				tabsMenuList.forEach((item, index) => {
					if (item.path !== tabPath) return;
					const nextTab = tabsMenuList[index + 1] || tabsMenuList[index - 1];
					if (!nextTab) return;
					router.push(nextTab.path);
				});
			}
			this.tabsMenuList = tabsMenuList.filter((item) => item.path !== tabPath);
		},
		// Close MultipleTab
		async closeMultipleTab(tabsMenuValue?: string) {
			this.tabsMenuList = this.tabsMenuList.filter((item) => {
				return item.path === tabsMenuValue || !item.close;
			});
		},
		async closeAllTabs() {
			this.tabsMenuList = this.tabsMenuList.filter((item) => {
				return item.path === '/' || item.path === '/dashboard/workspace';
			});
			await router.push('/');
		},
	},
	persist: piniaPersistConfig('TabsState'),
});
